<template>
  <view class="application-page">
    <view class="form">
      <!-- 办件类型 -->
      <view class="form-item">
        <text class="label">办件类型</text>
        <picker
          @change="handleTypeChange"
          :value="formData.typeIndex"
          :range="serviceTypes"
          range-key="name"
        >
          <view class="picker-value">
            {{
              (serviceTypes[formData.typeIndex] &&
                serviceTypes[formData.typeIndex].name) ||
              '请选择办件类型'
            }}
            <text class="iconfont arrow-down">▼</text>
          </view>
        </picker>
      </view>

      <!-- 申请人信息 -->
      <view class="form-item">
        <text class="label">申请人姓名</text>
        <input
          type="text"
          v-model="formData.name"
          placeholder="请输入申请人姓名"
        />
      </view>

      <view class="form-item">
        <text class="label">身份证号</text>
        <input
          type="idcard"
          v-model="formData.idCard"
          placeholder="请输入18位身份证号码"
          maxlength="18"
        />
      </view>

      <view class="form-item">
        <text class="label">性别</text>
        <picker
          @change="handleGenderChange"
          :value="formData.genderIndex"
          :range="genderOptions"
          range-key="name"
        >
          <view class="picker-value">
            {{
              (genderOptions[formData.genderIndex] &&
                genderOptions[formData.genderIndex].name) ||
              '请选择性别'
            }}
            <text class="iconfont arrow-down">▼</text>
          </view>
        </picker>
      </view>

      <view class="form-item">
        <text class="label">民族</text>
        <picker
          @change="handleNationalChange"
          :value="formData.nationalIndex"
          :range="nationalOptions"
          range-key="name"
        >
          <view class="picker-value">
            {{
              (nationalOptions[formData.nationalIndex] &&
                nationalOptions[formData.nationalIndex].name) ||
              '请选择民族'
            }}
            <text class="iconfont arrow-down">▼</text>
          </view>
        </picker>
      </view>

      <view class="form-item">
        <text class="label">联系电话</text>
        <input
          type="number"
          v-model="formData.phone"
          placeholder="请输入11位手机号码"
          maxlength="11"
          readonly
        />
      </view>

      <view class="form-item">
        <text class="label">住址</text>
        <input
          type="text"
          v-model="formData.address"
          placeholder="请输入详细地址"
        />
      </view>

      <!-- 附件上传 -->
      <view class="form-item">
        <text class="label">申请人材料</text>
        <view class="upload-box" @click="handleUpload">
          <text class="upload-text">点击上传附件</text>
          <text class="iconfont upload-icon">📎</text>
        </view>
        <!-- 文件列表 -->
        <view class="file-list" v-if="fileList.length > 0">
          <view
            class="file-item"
            v-for="(file, index) in fileList"
            :key="index"
          >
            <text class="file-name">{{ file.name }}</text>
            <text class="delete-btn" @click.stop="handleDeleteFile(index)"
              >×</text
            >
          </view>
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <button class="submit-btn" @click="handleSubmit">提交申请</button>
  </view>
</template>

<script>
import { getDict, submit } from '@/api/dict'
import { uploadBase64 } from '@/api/upload'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      serviceTypes: [],
      base64List: [],
      fileList: [],
      genderOptions: [
        { name: '男', value: '男' },
        { name: '女', value: '女' },
      ],
      nationalOptions: [
        { name: '汉族', value: '汉族' },
        { name: '蒙古族', value: '蒙古族' },
        { name: '回族', value: '回族' },
        { name: '藏族', value: '藏族' },
        { name: '维吾尔族', value: '维吾尔族' },
        { name: '苗族', value: '苗族' },
        { name: '彝族', value: '彝族' },
        { name: '壮族', value: '壮族' },
        { name: '布依族', value: '布依族' },
        { name: '朝鲜族', value: '朝鲜族' },
        { name: '满族', value: '满族' },
        { name: '侗族', value: '侗族' },
        { name: '瑶族', value: '瑶族' },
        { name: '白族', value: '白族' },
        { name: '土家族', value: '土家族' },
        { name: '哈尼族', value: '哈尼族' },
        { name: '哈萨克族', value: '哈萨克族' },
        { name: '傣族', value: '傣族' },
        { name: '黎族', value: '黎族' },
        { name: '傈僳族', value: '傈僳族' },
        { name: '佤族', value: '佤族' },
        { name: '畲族', value: '畲族' },
        { name: '高山族', value: '高山族' },
        { name: '拉祜族', value: '拉祜族' },
        { name: '水族', value: '水族' },
        { name: '东乡族', value: '东乡族' },
        { name: '纳西族', value: '纳西族' },
        { name: '景颇族', value: '景颇族' },
        { name: '柯尔克孜族', value: '柯尔克孜族' },
        { name: '土族', value: '土族' },
        { name: '达斡尔族', value: '达斡尔族' },
        { name: '仫佬族', value: '仫佬族' },
        { name: '羌族', value: '羌族' },
        { name: '布朗族', value: '布朗族' },
        { name: '撒拉族', value: '撒拉族' },
        { name: '毛南族', value: '毛南族' },
        { name: '仡佬族', value: '仡佬族' },
        { name: '锡伯族', value: '锡伯族' },
        { name: '阿昌族', value: '阿昌族' },
        { name: '普米族', value: '普米族' },
        { name: '塔吉克族', value: '塔吉克族' },
        { name: '怒族', value: '怒族' },
        { name: '乌孜别克族', value: '乌孜别克族' },
        { name: '俄罗斯族', value: '俄罗斯族' },
        { name: '鄂温克族', value: '鄂温克族' },
        { name: '德昂族', value: '德昂族' },
        { name: '保安族', value: '保安族' },
        { name: '裕固族', value: '裕固族' },
        { name: '京族', value: '京族' },
        { name: '塔塔尔族', value: '塔塔尔族' },
        { name: '独龙族', value: '独龙族' },
        { name: '鄂伦春族', value: '鄂伦春族' },
        { name: '赫哲族', value: '赫哲族' },
        { name: '门巴族', value: '门巴族' },
        { name: '珞巴族', value: '珞巴族' },
        { name: '基诺族', value: '基诺族' },
      ],
      formData: {
        typeIndex: 0,
        name: '',
        idCard: '',
        phone: '',
        address: '',
        attachment: '',
        genderIndex: 0,
        nationalIndex: 0,
        gender: '',
        national: '',
      },
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  watch: {
    userInfo: {
      handler(userInfo) {
        if (userInfo.userId) {
          this.getDict()
          this.formData.phone = userInfo.userId
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    getDict() {
      getDict().then(({ data }) => {
        this.serviceTypes = data.map((item) => ({
          name: item.dictValue,
          value: item.dictKey,
        }))
        console.log('办件类型：', this.serviceTypes)
      })
    },
    handleTypeChange(e) {
      this.formData.typeIndex = e.detail.value
    },
    handleGenderChange(e) {
      this.formData.genderIndex = e.detail.value
      this.formData.gender = this.genderOptions[e.detail.value].value
    },
    handleNationalChange(e) {
      this.formData.nationalIndex = e.detail.value
      this.formData.national = this.nationalOptions[e.detail.value].value
    },
    handleUpload() {
      uni.chooseFile({
        count: 9,
        success: (res) => {
          res.tempFiles.forEach((file) => {
            this.fileList.push({
              name: file.name,
              size: file.size,
            })

            const fileReader = new FileReader()
            fileReader.onload = (e) => {
              // 获取文件类型
              const fileType = this.getFileType(file.name)
              // 获取base64数据（去除头部）
              const base64 = e.target.result.split(',')[1]
              // 添加到base64List
              this.base64List.push({
                fileType,
                base64,
              })
            }
            fileReader.readAsDataURL(file)
          })

          this.formData.attachment = `已选择 ${this.fileList.length} 个文件`
        },
      })
    },
    // 根据文件名获取文件类型
    getFileType(fileName) {
      return fileName.split('.').pop().toLowerCase()
    },
    handleDeleteFile(index) {
      this.fileList.splice(index, 1)
      this.base64List.splice(index, 1)

      if (this.fileList.length === 0) {
        this.formData.attachment = ''
      } else {
        this.formData.attachment = `已选择 ${this.fileList.length} 个文件`
      }
    },
    async handleSubmit() {
      if (!this.validateForm()) {
        return
      }

      const applicantFiles = []
      for (const { base64, fileType } of this.base64List) {
        const res = await uploadBase64(base64, fileType)
        applicantFiles.push(res.data.url)
      }

      await submit({
        applicantName: this.formData.name,
        idNumber: this.formData.idCard,
        applicationPhone: this.formData.phone,
        applicationAddress: this.formData.address,
        applicantFiles: applicantFiles.join(','),
        serviceType: this.serviceTypes[this.formData.typeIndex].value,
        userId: this.userInfo.userId,
        gender: this.genderOptions[this.formData.genderIndex].value,
        national: this.nationalOptions[this.formData.nationalIndex].value,
      })

      // 提示成功
      uni.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000,
      })

      // 延迟返回，让用户看到成功提示
      setTimeout(() => {
        uni.navigateBack({
          delta: 1,
        })
      }, 1500)
    },
    validateForm() {
      if (!this.serviceTypes[this.formData.typeIndex]) {
        uni.showToast({
          title: '请选择办件类型',
          icon: 'none',
        })
        return false
      }

      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入申请人姓名',
          icon: 'none',
        })
        return false
      }

      if (!/^\d{17}[\dXx]$/.test(this.formData.idCard)) {
        uni.showToast({
          title: '请输入正确的身份证号',
          icon: 'none',
        })
        return false
      }

      if (!/^1\d{10}$/.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none',
        })
        return false
      }

      if (!this.formData.address.trim()) {
        uni.showToast({
          title: '请输入住址',
          icon: 'none',
        })
        return false
      }

      if (this.fileList.length === 0) {
        uni.showToast({
          title: '请上传申请人附件',
          icon: 'none',
        })
        return false
      }

      return true
    },
  },
}
</script>

<style lang="scss" scoped>
.application-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 16px;
}

.form {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;

  .form-item {
    margin-bottom: 20px;

    .label {
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      display: block;

      &::after {
        content: '*';
        color: #ff4d4f;
        margin-left: 4px;
      }
    }

    input {
      width: 100%;
      height: 44px;
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 0 12px;
      font-size: 14px;
      background-color: #fff;
      box-sizing: border-box;
    }

    .picker-value {
      width: 100%;
      height: 44px;
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 0 12px;
      font-size: 14px;
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #333;
      box-sizing: border-box;

      .arrow-down {
        font-size: 12px;
        color: #999;
      }
    }

    .file-list {
      margin-top: 12px;

      .file-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px 12px;
        background-color: #f5f5f5;
        border-radius: 4px;
        margin-bottom: 8px;

        .file-name {
          flex: 1;
          font-size: 14px;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          margin-right: 8px;
        }

        .delete-btn {
          width: 20px;
          height: 20px;
          line-height: 20px;
          text-align: center;
          border-radius: 50%;
          background-color: #ff4d4f;
          color: #fff;
          font-size: 16px;
          cursor: pointer;
        }
      }
    }

    .upload-box {
      width: 100%;
      height: 44px;
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 0 12px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #fff;
      box-sizing: border-box;
      cursor: pointer;
      .upload-text {
        font-size: 14px;
        color: #999;
      }

      .upload-icon {
        font-size: 20px;
        color: #999;
      }
    }
  }
}

.submit-btn {
  width: 100%;
  height: 44px;
  background-color: #66c2ff;
  color: #fff;
  border-radius: 22px;
  font-size: 16px;
  margin-top: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
